﻿using Common;
using Common.BMap;
using Common.JPush;
using Core;
using DAL.DAO;
using DAL.Models;
using UI.Filter;
using UI.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Mvc;
using UI.Areas.Api.Model;
using System.IO;
using log4net.Config;
using log4net;
using System.Configuration;
using Newtonsoft.Json.Linq;

namespace UI.Areas.Api.Controllers
{
    /// <summary>
    ///   ${table.comment}接口
    /// </summary>
    [TokenAuthentication]
    public class Api${ClassName}Controller : Controller
    {

        private ${TableName}DAO ${TableName}Dao { get; set; }

        private user_device_authorizationDAO user_device_authorizationDao { get; set; }

        private device_user_bindDAO device_user_bindDao { get; set; }

        private user_infoDAO user_infoDao { get; set; }


      

        public Api${ClassName}Controller()
        {

            if (${TableName}Dao == null)
            {
                ${TableName}Dao = new ${TableName}DAO();
            }

            if (user_device_authorizationDao == null)
            {
                user_device_authorizationDao = new user_device_authorizationDAO();
            }

            if (device_user_bindDao == null)
            {
                device_user_bindDao = new device_user_bindDAO();
            }

            if (user_infoDao == null)
            {
                user_infoDao = new user_infoDAO();
            }



        }



        #region 查询
        /// <summary>
        /// 查询该用户下所有设备
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetDevices(string appid, string page = "1", string rows = "10")
        {
            long user_id = user_infoDao.GetUserInfoByAppid(appid).id;

            // 检查用户有无绑定该类设备的权限
            var auth = user_device_authorizationDao.GetAuthByUser(user_id,Codebooks.CODE_${TableNameUpper});
            if (auth == null || !CheckHelper.CheckAuth(auth.valid.Value, auth.exp_from, auth.exp_to))
                return Json(new ApiResultModel("用户没有该类设备的授权"), JsonRequestBehavior.AllowGet);

            int total = 0, records = 0;
            var devices = ${TableName}Dao.GetByUser(user_id, page.ToInt32(), rows.ToInt32(), ref total, ref records);

            if (devices == null)
                return Json(new ApiResultModel("该用户没有绑定的设备"), JsonRequestBehavior.AllowGet);

            List<object> data = new List<object>();
            foreach (${TableName} device in devices)
            {
                data.Add(new
                {
                    id = device.id,
                    sn = device.imei,
                    submit_time = device.submit_time,
                    creator= device.creator,
                    update_date = device.update_date
                });
            }

            return Json(new ApiResultModel
            {
                data = data
            }, JsonRequestBehavior.AllowGet);
        }


     

        /// <summary>
        /// 根据sn查询设备
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="mac"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetDeviceBySn(string appid, string imei)
        {
            var args = ValidateHelper.IsNotNullOrEmpty(imei);
            if (!args.Flag)
                return Json(new ApiResultModel(ErrorCode.ParamsLack), JsonRequestBehavior.AllowGet);

            long user_id = user_infoDao.GetUserInfoByAppid(appid).id;

            //获取设备信息
            var device = ${TableName}Dao.GetByImei(imei);
            if (device == null)
                return Json(new ApiResultModel("无设备信息"), JsonRequestBehavior.AllowGet);


            var relation = device_user_bindDao.GetRelationByDivice(device.id, Codebooks.CODE_${TableNameUpper});
            if (relation.user_id != user_id)
                return Json(new ApiResultModel("该设备不在用户权限内"), JsonRequestBehavior.AllowGet);

            var result = new
            {
                id = device.id,
                imei = device.imei,
                submit_time = device.submit_time,
                update_date = device.update_date
            };


            return Json(new ApiResultModel
            {
                data = result
            }, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 绑定/解绑

        /// <summary>
        /// 绑定
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="imei"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Bind(string appid, string imei)
        {
            var args = ValidateHelper.IsNotNullOrEmpty(imei);
            if (!args.Flag)
                return Json(new ApiResultModel(ErrorCode.ParamsLack));

            var user_id = user_infoDao.GetUserInfoByAppid(appid).id;

            // 检查用户有无绑定该类设备的权限
            var auth = user_device_authorizationDao.GetAuthByUser(user_id,Codebooks.CODE_${TableNameUpper});
            if (auth == null || !CheckHelper.CheckAuth(auth.valid.Value, auth.exp_from, auth.exp_to))
                return Json(new ApiResultModel("用户没有该类设备的授权"));

            var device = ${TableName}Dao.GetByImei(imei);

            if (device == null)
            {
                // 增加设备,并与用户绑定
                ${TableName} model = new ${TableName}
                {
                    imei = imei,
                    creator = user_id,
                    create_date = DateTime.Now,
                    model= "${table.comment}"

                };
                args = ${TableName}Dao.Add(model);
                if (!args.Flag)
                    return Json(new ApiResultModel(args.Msg));

                args = device_user_bindDao.Add(new device_user_bind
                {
                    device_id = model.id,
                    device_type = Codebooks.CODE_${TableNameUpper},
                    user_id = user_id,
                    creator = user_id,
                    create_date = DateTime.Now
                });
                if (!args.Flag)
                {
                    return Json(new ArgsHelper(false, args.Msg));
                }

            }
            else
            {
                var relation = device_user_bindDao.GetRelationByDivice(device.id, Codebooks.CODE_${TableNameUpper});

                if (relation != null)
                {
                    if (relation.user_id != user_id)
                    {
                        return Json(new ApiResultModel("该设备不属于用户"));
                    }
                }
                else
                {
                    // 将设备与用户绑定
                    args = device_user_bindDao.Add(new device_user_bind
                    {
                        device_id = device.id,
                        device_type = Codebooks.CODE_${TableNameUpper},
                        user_id = user_id,
                        creator = user_id,
                        create_date = DateTime.Now
                    });
                    if (!args.Flag)
                    {
                        return Json(new ArgsHelper(false, args.Msg));
                    }
                }
            }

            return Json(new ApiResultModel() { result = true, message = "绑定成功" });
        }


        /// <summary>
        /// 解绑
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="imei"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UnBind(string appid, string imei)
        {
            var args = ValidateHelper.IsNotNullOrEmpty(imei);
            if (!args.Flag)
                return Json(new ApiResultModel(ErrorCode.ParamsLack));

            var user_id = user_infoDao.GetUserInfoByAppid(appid).id;

            // 检查用户有无绑定该类设备的权限
            var auth = user_device_authorizationDao.GetAuthByUser(user_id,Codebooks.CODE_${TableNameUpper});
            if (auth == null || !CheckHelper.CheckAuth(auth.valid.Value, auth.exp_from, auth.exp_to))
                return Json(new ApiResultModel("用户没有该类设备的授权"));

            var device = ${TableName}Dao.GetByImei(imei);
            if (device == null)
                return Json(new ApiResultModel() {  result = true, message = "解绑成功"  });

            var relation = device_user_bindDao.GetRelationsByUserAndDevice(user_id,  Codebooks.CODE_${TableNameUpper}, device.id);
            if (relation == null)
                return Json(new ApiResultModel("用户无权限操作该设备"));


            // 解决与用户的绑定关系
            args = device_user_bindDao.Delete(relation.id);

            return Json(new ApiResultModel() {  result = true, message = "解绑成功"  });
        }

        #endregion

     

        #region 工具函数
        /// <summary>
        /// 生成6位指定流水号
        /// </summary>
        /// <returns></returns>
        private string MakeCmdSeq()
        {
            // 取时分秒 6位
            return DateTime.Now.ToString("HHmmss");
        }
        #endregion








    

        /// <summary>
        /// 检查合法用户
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="sn"></param>
        /// <returns></returns>
        public ApiResultModel CheckUser(string appid, string sn) {

            var args = ValidateHelper.IsNotNullOrEmpty(appid,sn);
            if (!args.Flag)
                return new ApiResultModel(ErrorCode.ParamsLack);

            var user_id = user_infoDao.GetUserInfoByAppid(appid).id;

            // 检查用户有无绑定该类设备的权限
            var auth = user_device_authorizationDao.GetAuthByUser(user_id, Codebooks.CODE_${TableNameUpper});
            if (auth == null || !CheckHelper.CheckAuth(auth.valid.Value, auth.exp_from, auth.exp_to)) {
                return new ApiResultModel("用户没有该类设备的授权");
            }

            var device = ${TableName}Dao.GetByImei(sn);
            if (device == null)
                return new ApiResultModel("无该设备信息");

            var relation = device_user_bindDao.GetRelationsByUserAndDevice(user_id, Codebooks.CODE_${TableNameUpper}, device.id);
            if (relation == null)
                return new ApiResultModel("用户无权限操作该设备");


            return new ApiResultModel();

        }

    }
}
